#coding=utf-8
import cookielib
import urllib
import urllib2
import string

import re,time,md5,base64
import os,sys

def inner_response(error, result, message=""):
	return {'error':error,'result':result,'message': message}

class ZF():
	def __init__(self,setting):
		self.setting = setting

		self.cookies = cookielib.LWPCookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
		urllib2.install_opener(self.opener)
		urllib2.socket.setdefaulttimeout(20)

		self.base_url  = self.setting['base_url']
		self.login_url = self.base_url + self.setting['login_aspx']
		self.code_url  = self.base_url + 'CheckCode.aspx'

		self.headers = {
			'Referer'   :self.login_url,
			'Host'      :self.setting['host'],
			'User-Agent':"Mozilla/5.0 (X11; Ubuntu; Linux i686;rv:18.0) Gecko/20100101 Firefox/18.0",
			'Connection':'Keep-Alive'
		}

		self.username  = ""
		self.VIEWSTATE = ""

	def pre(self):

		try:
			request  = urllib2.Request(self.login_url,headers=self.headers)
			body = self.opener.open(request).read().decode("gbk").encode("utf-8")
		except:
			return inner_response(True,"systemTimeOut","login_url连接超时！")

		viewstate = re.compile(r'name="__VIEWSTATE" value="(.*?)"').findall(body)

		try:
			self.VIEWSTATE =  viewstate[0]
		except:
			return inner_response(True,"","接口错误！")

		#生成token
		self.token = md5.md5(str(time.time())+self.VIEWSTATE).hexdigest()

		result = {
			'username' : '',
			'password' : '',
			'token'    : self.token
		}

		#获取验证码
		if body.find('验证码') != -1:
			try:
				request  = urllib2.Request(self.code_url,headers = self.headers)
				body = self.opener.open(request).read()
				result['code_row'] = 'data:image/gif;base64,'+base64.b64encode(body)
				result['code']     = ''
			except:
				return inner_response(True,"systemTimeOut","CheckCode.aspx连接超时！")

		return inner_response(False,result)

	def login(self, request):
		self.username = request['username']

		if(self.setting["login_aspx"] == "Default6.aspx"):
			data = {
				'tname':"",
				'tbtns':"",
				'txtXm':"",
				'tnameXw':"yhdl",
				'tbtns':"yhdl|xwxsdl",
				'rblJs':"学生",
				'btnDl':"登 录",
				'txtYhm':request['username'],
				'txtMm':request['password'],
				'__VIEWSTATE':self.VIEWSTATE,	
			}
		else:
			data = {
				'Button1':'',
				'RadioButtonList1':"学生",
				'txtUserName':request['username'],
				'TextBox2':request['password'],
				'__VIEWSTATE':self.VIEWSTATE,
				'lbLanguage':'',
			}
			if request.has_key('code'):
				data["txtSecretCode"] = request['code'].decode("utf-8").encode("gb2312")

		try:
			post_data = urllib.urlencode(data)
			request   = urllib2.Request(self.login_url,post_data,self.headers)
			body      = self.opener.open(request).read().decode("gbk").encode("utf-8")
		except:
			return inner_response(True,"systemTimeOut","login_url提交超时！")
		
		if body.find('欢迎您') != -1:
			return inner_response(False,"","登陆成功!")
		elif body.find('用户名不存在') != -1:
			return inner_response(True,"","该教务系统未找到您的信息!")
		elif body.find('密码错误') != -1:
			return inner_response(True,"","密码错误!")
		elif body.find('验证码不正确') != -1:
			return inner_response(True,"","验证码不正确!")
		elif body.find('需修改后才能登陆') != -1:
			return inner_response(True,"","密码过弱，请到教务系统修改密码后登陆!")
		else:
			return inner_response(True,body,"未知错误!")

	def get_html(self, path, data={}, decode=True):
		post_data = urllib.urlencode(data)
		url = self.base_url + path + ".aspx?xh=" + self.username
		try:
			request = urllib2.Request(url, post_data, self.headers)
			body    = self.opener.open(request).read()
			if decode:
				body = body.decode('gbk').encode("utf-8")
			
			if body.find('验证码') != -1:
				return inner_response(True,"tokenTimeOut","验证码失效！")

			if body.find('未评价') != -1:
				return inner_response(True,"teachUnComment","有教师未评价！")

			if body.find('还没有进行本学期的教学质量评价') != -1:
				return inner_response(True,"courseUnComment","有课程未评价！")

			return inner_response(False,body)
		except:
			return inner_response(True,"systemTimeOut","get_html连接超时！")

	def get_main(self):
		'''
		个人主页
		'''
		return self.get_html("xs_main")

	def get_info(self):
		'''
		个人信息
		'''
		response = self.get_html("xsgrxx")

		if not response['error']:
			path = os.path.abspath(os.path.dirname(sys.argv[0]))
			file_path = path + '/info/' + self.username
			f = file(file_path,'wb')
			f.write(response["result"])
			f.close()

		return response

	def get_photo(self):
		'''
		照片
		'''
		response = self.get_html("readimagexs",{},False)
		if not response['error']:
			path = os.path.abspath(os.path.dirname(sys.argv[0]))
			file_path = path + '/photo/' + self.username + '.gif'
			f = file(file_path,'wb')
			f.write(response["result"])
			f.close()

			response['result'] = 'data:image/gif;base64,'+base64.b64encode(response["result"])

		return response

	def get_table(self):
		'''
		课表
		'''
		return self.get_html("xskbcx")

	def get_exam(self):
		'''
		考试
		'''
		return self.get_html("xskscx")

	def get_score(self):
		'''
		成绩
		'''
		if( self.setting["name"] == "guoren" ):
			response = self.get_html("xscjcx")
			if response["error"]:
				return response
			com = re.compile(r'name="__VIEWSTATE" value="(.*?)"')
			viewstate = com.findall(response['result'])
			data = {
				'hidLanguage':'',
				'ddlXN':'',
				'ddlXQ':'',
				'ddl_kcxz':'',
				'btn_zcj':'1',
				'__VIEWSTATE':viewstate[0],
				'__EVENTTARGET':'',
				'__EVENTARGUMENT':'',
			}
			return self.get_html("xscjcx",data)
		else:
			response = self.get_html("xscj_gc")
			if response["error"]:
				return response
			com = re.compile(r'name="__VIEWSTATE" value="(.*?)"')
			viewstate = com.findall(response['result'])
			data = {
				'ddlXN':'',
				'ddlXQ':'',
				'Button2':'1',
				'__VIEWSTATE':viewstate[0],
			}
			return self.get_html("xscj_gc",data)